﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Web.Enhancements.Rest.Templates
{
    /// <summary>
    /// Class that provides ability to return data through REST services that should be 
    /// processed as JSON-formatted data to respond back to the client. 
    /// This class uses DataContract to output the JSON data.
    /// </summary>
    internal class CustomJsonTemplate : ITemplatedResult
    {
        /// <summary>
        /// Gets or sets result data that should be returned to the client.
        /// </summary>
        public object ResultData { get; set; }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public CustomJsonTemplate()
        {
        }

        /// <summary>
        /// Contsractor that accpets result data that class should process into JSON response.
        /// </summary>
        /// <param name="resultData">Result data as an object</param>
        public CustomJsonTemplate(object resultData)
        {
            this.ResultData = resultData;
        }

        /// <summary>
        /// Method converts ResultData object to JSON format and renders content into given HTTP response object.
        /// </summary>
        /// <param name="response">HTTP response object.</param>
        public void RenderResult(System.Web.HttpResponse response)
        {
            if (WebRestSettings.Current.CustomJsonSerializerProvider == null)
                throw new WebRestException("The use of CustomJsonSerializer is requested, but CustomJsonSerializerProvider is not configured properly.");

            ICustomJsonSerializer jsonSerializer = WebRestSettings.Current.CustomJsonSerializerProvider.CreateJsonSerializer(this.ResultData.GetType());
            jsonSerializer.Serialize(response.Output, this.ResultData);
        }
    }
}
